<template>
  <!-- 编辑器 -->
  <!-- 每个步骤（任务）都是canvas，线条也是canvas（只能直线） -->
  <div class="vetl-editor" v-on:contextmenu.prevent="contextMenu">

    <!-- -->
    <!-- <canvas class="vetl-editor-canvas">

    </canvas> -->
    <div class="vetl-editor-stage" v-on:drop="drop" v-on:dragover="allowDrop">

      <!-- 步骤 -->
      <component v-bind:is="step.component" 
      v-bind:name="step.name" v-bind:position="step.position"
      v-for="step in steps" :key="step.name"></component>

      <!-- 连接线 -->
      <component v-bind:is="connectLine" 
      v-bind:startPosition="line.startPosition"
      v-for="line in lines" :key="line.name"></component>
    </div>
  </div>
</template>

<script>
import step from './step'
import connectLine from './line'


export default {
  name: "editor",
  components: {step, connectLine},
  data() {
    return {
      steps: [],
      lines: []
    };
  },
  methods: {
    drop(event) {
      event.preventDefault()

      //获取事件的位置 x ，y
      //添加一个步骤，设置他的位置在这个地方
      let editorRect = event.currentTarget.getBoundingClientRect()
      let left = event.clientX - editorRect.x;
      let top = event.clientY - editorRect.y;

      //判断
      var opration = event.dataTransfer.getData("opration")
      if(opration === 'move'){
        let name = event.dataTransfer.getData("name")
        
        for(var step of this.steps){
          if(step.name === name){
            step.position.left = left;
            step.position.top = top;
          }
        }
      }else{
        let name = event.dataTransfer.getData("name");
        let type = event.dataTransfer.getData("type");
        var step = {
          name: this.getUnipueName(type, name),
          position: {
            left: left,
            top: top
          },
          component: 'step',
          type: type
        }
        this.steps.push(step);
      }
    },
    allowDrop(event) {
      event.preventDefault()
    },
    getUnipueName(type, name){
      var count = 0;
      for(var step of this.steps){
        if(step.type === type){
          count++;
        }
      }
      if(count){
        name = name + "" + count;
      }

      return name;
    },
    contextMenu(event){
      //event.preventDefault();
      
      document.addEventListener("click", this.hideMenu);
    },
    hideMenu(){
      
      document.removeEventListener("click", this.hideMenu)
    }
  }
};
</script>

<style>
.vetl-editor {
  background-color: aquamarine;
}
.vetl-editor-canvas {
  position: relative;
}
.vetl-editor-stage{
  position: relative;
  width: 100%;
  height: 100%;
}
</style>